<script setup>
import { ref, onMounted, getCurrentInstance, watch, computed } from 'vue'
import api from '@/api/index.js'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: ''
  },
  params: {
    type: Object,
    default: () => ({
      outBigTypeId: '',
      outSmallTypeId: '',
    })
  },
  apiName: {
    type: String,
    default: 'getWuziList'
  },
  dataProp: {
    type: [String, Array],
    default: 'data'
  }
})

const attrs = ref({})

onMounted(() => {
  const { ctx } = getCurrentInstance()
  const attrs = ref({})
  attrs.value = ctx.$attrs
})

const sltVal = ref('')

const change = e => {
  emits('update:modelValue', e)
}

const options = ref([])

const objBind = computed(() => {
  return {
    options: options.value,
    ...attrs.value
  }
})

const getOptions = async para => {
  // if (para.outBigTypeId && para.outSmallTypeId) {
  const res = await api[props.apiName](para)
  if (typeof props.dataProp === 'string') {
    options.value = res[props.dataProp]
  } else if (Array.isArray(props.dataProp)) {
    let resultObj = res
    options.value = res[props.dataProp[0][1]]
    props.dataProp.forEach((item) => {
      resultObj = resultObj[item]
    })
    options.value = resultObj
  }
  // } else {
  // options.value = []
  // }
}

watch(() => props.modelValue, val => {
  sltVal.value = val
}, { immediate: true })

watch(() => props.params, p => {
  getOptions(p)
}, { deep: true, immediate: true })
</script>

<template>
  <a-cascader v-bind="objBind" v-model:value="sltVal" @change="change" />
</template>